import { _decorator, Component, Node, v3, Vec2, Vec3 } from 'cc';
import { GlobalEnum } from '../../../Init/Config/GlobalEnum';
import EventManager from '../../../Init/Managers/EventManager';
import { EventTypes } from '../../../Init/Managers/EventTypes';
import GlobalPool from '../../../Init/Tools/GlobalPool';
import { MappingObj } from './MappingObj';
import { TankAnim } from './TankAnim';
const { ccclass, property } = _decorator;

@ccclass('MappingTank')
export class MappingTank extends MappingObj {
    _anim: TankAnim = null;
    _rot = v3();
    _tower: Node = null;
    init() {
        this._tower = this.node.children[0].children[0].getChildByName('TankFree_Tower');
        this._anim = new TankAnim(this.node.children[0], this._tower);
        this._anim.reset();
        this._anim.setData(this._rot);

        //位置
        this.tmpP.set(this.mappingProps.node.position);
        this.tmpP.z = -this.tmpP.y;
        this.tmpP.y = 0;
        this.node.setPosition(this.tmpP.multiplyScalar(this.s3d));

        this.updateProp();
        this.onEvents();
    }

    onEvents() {
        EventManager.on(EventTypes.EffectEvents.ShowTankShootEffect, this.onShowShootEffect, this);

    }

    reset(): void {
        GlobalPool.put(this.node);
        EventManager.off(EventTypes.EffectEvents.ShowTankShootEffect, this.onShowShootEffect, this);
    }

    update(dt: any): void {
        super.update(dt);
        this._anim && this._anim.updateAnim(dt);
    }

    updateProp() {

        //旋转
        this.tmpR.x = 0;
        this.tmpR.z = 0;
        if (Math.abs(this.mappingProps.node.eulerAngles.x) == 180) {
            this.tmpR.y = -(this.mappingProps.node.eulerAngles.z % 360) + 180;
        } else {
            this.tmpR.y = this.mappingProps.node.eulerAngles.z;
        }
        this.tmpR.y += 180;
        this._rot.y = this.tmpR.y;

        //状态切换
        this._anim &&
            this._anim.changeState(this.mappingProps.node[GlobalEnum.ExtralProp.customProps].state);
    }
    //发射效果
    tmpP = v3();
    onShowShootEffect(d: { uuid: string, toP: Vec3, t: number }) {
        if (!!this.mappingProps.node && d.uuid == this.mappingProps.node.uuid) {
            let node = this._tower.getChildByName('GunEnd');
            // let fromNode = this._tower.getChildByName('Direc');
            this.tmpP.set(node.worldPosition);
            // this.tmpP.y = 0;
            //效果
            if (this._anim) {
                EventManager.emit(EventTypes.EffectEvents.show2DEffect, { t: GlobalEnum.Effect2DType.TankShoot, p: this.tmpP, });
            }
            //导弹3d
            d['p'] = node.worldPosition;
            EventManager.emit(EventTypes.Mapping3DEvents.SetMissiles, d);
        }
    }

}

